//
//  ZZCImmovablePropertyController.m
//  ZZC-Finance
//
//  Created by a on 2017/8/11.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ZZCImmovablePropertyController.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface ZZCImmovablePropertyController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *ImmovablePropetryWebV;
@property (strong, nonatomic) NSURL *uurl;
@property (copy,   nonatomic) NSString *imgUrl;

@end

@implementation ZZCImmovablePropertyController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    float chacha = [[NSUserDefaults standardUserDefaults] floatForKey:@"appchacha"];
    chacha += 0.01;
    [[NSUserDefaults standardUserDefaults] setFloat:chacha forKey:@"appchacha"];

    self.navigationController.delegate = self;
    self.ImmovablePropetryWebV.delegate = self;
    // Do any additional setup after loading the view from its nib.
    NSString *token = ZZCNSUserDefaults(@"token");
    NSURL *h5_assetStatus = [NSURL URLWithString:[NSString stringWithFormat:@"%@&token=%@",ZZCURL_API_H5_ASSET_IMMOVABLE,token]];
    NSURLRequest *request = [NSURLRequest requestWithURL:h5_assetStatus];
    NSLog(@"%@",h5_assetStatus);
    //让内容自动适应屏幕大小
    self.ImmovablePropetryWebV.scrollView.bounces = NO;
    self.ImmovablePropetryWebV.scalesPageToFit = YES;
    [self.ImmovablePropetryWebV loadRequest:request];
    [self.view addSubview:self.ImmovablePropetryWebV];
    
    
    
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%@",request);
    if ([request.URL.absoluteString containsString:@"http://www.stlh.com/action===back"]) {
        NSLog(@"已拦截");
        [self.navigationController popToRootViewControllerAnimated:YES];
        
        
        return NO;
        
    }
    if ([request.URL.absoluteString containsString:@"http://www.stlh.com/action===photo"]) {
        [self userEvent];
        //        NSString *methodName = @"photo";
        
        
        return NO;
    }
    return YES;
    
}
//调用相机
- (void)userEvent {
    [self cameraBtnDidClick];
    //    NSString * str = [NSString stringWithFormat:@"photo_cancel('%@')",_imgUrl];
    //    NSString *str = @"photo_cancel()";
    //    [self.assetStatusWebV stringByEvaluatingJavaScriptFromString:str];
    
}

-(void)cameraBtnDidClick{
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    alertController.view.tintColor = [UIColor colorWithHex:0xEB6927];
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self openPhotoWithType:1];
    }];
    
    UIAlertAction * choice = [UIAlertAction actionWithTitle:@"相册选择" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self openPhotoWithType:0];
    }];
    
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    
    [alertController addAction:photo];
    [alertController addAction:choice];
    [alertController addAction:cancel];
    [self showDetailViewController:alertController sender:nil];
    
}

#pragma mark - 相册 相机
- (void)openPhotoWithType:(int)type
{
    if ([self getMediaTypeVideo]) {  //获取相机权限
        UIImagePickerControllerSourceType sourceType = type;
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.delegate = self;
        picker.allowsEditing = YES;//设置可编辑
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    }else{
        [[[UIAlertView alloc] initWithTitle:nil
                                    message:@"请设置使用照片。\n请启用照片-设置/隐私/照片"
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
        
        NSLog(@"相机受限");
    }
}

#pragma mark 判断摄像头权限
-(bool)getMediaTypeVideo
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    
    if(author == ALAuthorizationStatusRestricted){// 受限制 家长权限之类的
        
        return NO;
        
    } else if(author == ALAuthorizationStatusDenied){// 已经拒绝的
        
        [[[UIAlertView alloc] initWithTitle:nil
                                    message:@"请设置使用照片。\n请启用照片-设置/隐私/照片"
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
        return NO;
    } else if(author == ALAuthorizationStatusAuthorized){// 已允许的
        
        return YES;
        
    } else if(author == ALAuthorizationStatusNotDetermined){// 还没决定的
        
        return YES;
    } else {
        
        return NO;
    }
}
#pragma mark - imagePicker delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *img = [self scaleToSize:[info objectForKey:@"UIImagePickerControllerEditedImage"] size:CGSizeMake(300, 300)];
    ZZCLog(@"%@",img);
    [self uploadImage:img];
    
}
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


#pragma mark - 上传图片
- (void)uploadImage:(UIImage *)img {
    NSString *token = ZZCNSUserDefaults(@"token");
    NSDictionary *param = @{@"token":token,@"type":@(2)};
    [[ZZCRequest sharedNetworkTools] uploadWithURL:ZZCURL_API_UPLOAD params:param formBoundary:img success:^(NSDictionary * _Nonnull data) {
        ZZCLog(@"%@",data);
        self.imgUrl = [NSString stringWithFormat:@"%@%@",ZZCURL_API,data[@"data"][@"url"]];
        NSLog(@"       +++++++++++++++%@",_imgUrl);
        NSString * strr = [NSString stringWithFormat:@"photo('%@')",_imgUrl];
        [self.ImmovablePropetryWebV stringByEvaluatingJavaScriptFromString:strr];
        
    } fail:^(NSError * _Nonnull error, NSString * _Nonnull msg, NSDictionary * _Nonnull data) {
        ZZCLog(@"%@",error);
        NSString * strr = [NSString stringWithFormat:@"photo_cancel()"];
        [self.ImmovablePropetryWebV stringByEvaluatingJavaScriptFromString:strr];
        
    }];
    
}
- (void)getImage {
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) { //调用相册
        //实例化控制器
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        // 是否有图片选取框
        picker.allowsEditing = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
